package club.janna.springboot.study.processor;

import club.janna.springboot.study.service.AopHelloService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class HelloBeanProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof AopHelloService)
            return Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(), new HelloServiceHandler(bean));
        return bean;
    }

    private static class HelloServiceHandler implements InvocationHandler {

        private Object target;

        public HelloServiceHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            sb.append(method.invoke(target, args));
            sb.append("}");
            return sb.toString();
        }
    }
}
